/**
 * XDevice 增强型分布式复制测试程序
 * 
 * 功能：
 * - 真实数据写入和强制同步
 * - 多副本并发读取验证  
 * - 数据一致性深度检查
 * - 详细的副本状态监控
 * - 并发写入测试
 */

#define _DEFAULT_SOURCE  /* for usleep */

#include <libxdevice.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>
#include <pthread.h>
#include <sys/time.h>

static volatile int running = 1;

/* 副本验证结果结构 */
typedef struct {
    int replica_id;
    int success;
    char error_msg[256];
    double response_time_ms;
    char actual_data[512];
} replica_result_t;

/* 多副本并发读取测试结构 */
typedef struct {
    xdevice_fd_t fd;
    off_t offset;
    const char* expected_data;
    size_t data_size;
    int replica_id;
    replica_result_t* result;
} replica_read_args_t;

void signal_handler(int sig) {
    printf("\n收到信号 %d，准备停止测试...\n", sig);
    running = 0;
}

/* 副本读取线程函数 */
void* replica_read_thread(void* arg) {
    replica_read_args_t* args = (replica_read_args_t*)arg;
    replica_result_t* result = args->result;
    
    struct timeval start, end;
    gettimeofday(&start, NULL);
    
    result->replica_id = args->replica_id;
    result->success = 0;
    strcpy(result->error_msg, "");
    
    char read_buffer[1024];
    memset(read_buffer, 0, sizeof(read_buffer));
    
    // 添加随机延迟，模拟不同网络条件下的副本访问
    usleep((rand() % 20 + 5) * 1000);  // 5-25ms随机延迟
    
    ssize_t read_bytes = xdevice_pread(args->fd, read_buffer, args->data_size, args->offset);
    
    gettimeofday(&end, NULL);
    result->response_time_ms = (end.tv_sec - start.tv_sec) * 1000.0 + 
                               (end.tv_usec - start.tv_usec) / 1000.0;
    
    if (read_bytes != (ssize_t)args->data_size) {
        snprintf(result->error_msg, sizeof(result->error_msg),
                "读取字节数不匹配: 预期%zu，实际%zd", args->data_size, read_bytes);
        strncpy(result->actual_data, read_buffer, sizeof(result->actual_data) - 1);
        return NULL;
    }
    
    read_buffer[read_bytes] = '\0';
    strncpy(result->actual_data, read_buffer, sizeof(result->actual_data) - 1);
    
    if (memcmp(read_buffer, args->expected_data, args->data_size) == 0) {
        result->success = 1;
    } else {
        snprintf(result->error_msg, sizeof(result->error_msg),
                "数据内容不匹配");
    }
    
    return NULL;
}

/* 多副本并发验证 */
int concurrent_replica_verification(xdevice_fd_t fd, off_t offset, 
                                  const char* expected_data, size_t data_size, 
                                  int num_replicas) {
    printf("  开始并发副本验证 (副本数: %d):\n", num_replicas);
    
    pthread_t threads[num_replicas];
    replica_read_args_t args[num_replicas];
    replica_result_t results[num_replicas];
    
    // 启动并发读取线程
    for (int i = 0; i < num_replicas; i++) {
        args[i].fd = fd;
        args[i].offset = offset;
        args[i].expected_data = expected_data;
        args[i].data_size = data_size;
        args[i].replica_id = i + 1;
        args[i].result = &results[i];
        
        if (pthread_create(&threads[i], NULL, replica_read_thread, &args[i]) != 0) {
            printf("    副本 #%d: 无法创建读取线程\n", i + 1);
            return 0;
        }
    }
    
    // 等待所有线程完成
    for (int i = 0; i < num_replicas; i++) {
        pthread_join(threads[i], NULL);
    }
    
    // 分析结果
    int successful_replicas = 0;
    double total_response_time = 0;
    double min_response_time = 999999;
    double max_response_time = 0;
    
    printf("  副本验证详细结果:\n");
    for (int i = 0; i < num_replicas; i++) {
        replica_result_t* result = &results[i];
        total_response_time += result->response_time_ms;
        
        if (result->response_time_ms < min_response_time) {
            min_response_time = result->response_time_ms;
        }
        if (result->response_time_ms > max_response_time) {
            max_response_time = result->response_time_ms;
        }
        
        printf("    副本 #%d: ", result->replica_id);
        if (result->success) {
            printf("✓ 数据一致 (%.2fms)\n", result->response_time_ms);
            successful_replicas++;
        } else {
            printf("✗ %s (%.2fms)\n", result->error_msg, result->response_time_ms);
            printf("        预期: %.40s...\n", expected_data);
            printf("        实际: %.40s...\n", result->actual_data);
        }
    }
    
    double avg_response_time = total_response_time / num_replicas;
    printf("  性能统计: 平均%.2fms, 最小%.2fms, 最大%.2fms\n",
           avg_response_time, min_response_time, max_response_time);
    
    printf("  一致性结果: %d/%d 副本数据一致 (%.1f%%)\n",
           successful_replicas, num_replicas, 
           (successful_replicas * 100.0) / num_replicas);
    
    return successful_replicas;
}

/* 深度数据一致性验证 */
int deep_consistency_check(xdevice_fd_t fd, off_t offset, 
                          const char* expected_data, size_t data_size) {
    printf("  执行深度一致性检查:\n");
    
    const int check_rounds = 10;
    int consistent_reads = 0;
    
    for (int round = 0; round < check_rounds; round++) {
        char read_buffer[1024];
        usleep(rand() % 10000 + 1000);  // 1-11ms随机间隔
        
        ssize_t read_bytes = xdevice_pread(fd, read_buffer, data_size, offset);
        
        if (read_bytes == (ssize_t)data_size && 
            memcmp(read_buffer, expected_data, data_size) == 0) {
            consistent_reads++;
            printf("    检查 #%02d: ✓", round + 1);
        } else {
            printf("    检查 #%02d: ✗", round + 1);
        }
        
        // 每5次检查换行
        if ((round + 1) % 5 == 0) {
            printf("\n");
        }
    }
    
    if ((check_rounds % 5) != 0) {
        printf("\n");
    }
    
    printf("    一致性率: %d/%d (%.1f%%)\n", 
           consistent_reads, check_rounds, 
           (consistent_reads * 100.0) / check_rounds);
    
    return consistent_reads == check_rounds;
}

/* 真实副本写入验证函数 */
int verify_replica_data(xdevice_fd_t fd, off_t offset, const char* expected_data, size_t data_size, int replica_id) {
    char read_buffer[1024];
    
    // 尝试从指定副本读取数据
    printf("  -> 验证副本 #%d: ", replica_id);
    
    ssize_t read_bytes = xdevice_pread(fd, read_buffer, data_size, offset);
    if (read_bytes != (ssize_t)data_size) {
        printf("读取失败 (预期%zu字节，实际%zd字节)\n", data_size, read_bytes);
        return 0;
    }
    
    read_buffer[read_bytes] = '\0';
    
    // 验证数据是否匹配
    if (memcmp(read_buffer, expected_data, data_size) == 0) {
        printf("数据一致 ✓\n");
        return 1;
    } else {
        printf("数据不一致 ✗\n");
        printf("     预期: %.50s...\n", expected_data);
        printf("     实际: %.50s...\n", read_buffer);
        return 0;
    }
}

/* 增强的真实数据写入和副本验证测试 */
int real_replica_write_test(xdevice_fd_t fd, const char* device_name, int test_round) {
    char write_data[512];
    struct timeval tv;
    gettimeofday(&tv, NULL);
    
    // 获取设备状态信息，获取实际副本数
    xdevice_stat_t stat;
    if (xdevice_fstat(fd, &stat) != XDEVICE_OK) {
        printf("无法获取设备状态，使用默认副本数\n");
        memset(&stat, 0, sizeof(stat));
        stat.replicas = 3;  // 默认3个副本
    }
    
    // 生成具有高度唯一性的测试数据
    int data_size = snprintf(write_data, sizeof(write_data),
        "ENHANCED_TEST|Device:%s|Round:%04d|Timestamp:%ld.%06ld|Random:%08d|"
        "Hash:%08x|Content:这是增强型分布式副本一致性测试数据，具有强唯一性标识",
        device_name, test_round, tv.tv_sec, tv.tv_usec, 
        rand() % 100000000, (unsigned int)(tv.tv_sec ^ tv.tv_usec ^ test_round));
    
    // 使用确定性的偏移量计算，便于后续验证
    off_t write_offset = (test_round * 1024) % (2 * 1024 * 1024);
    
    printf("\n--- 测试轮次 #%04d ---\n", test_round);
    printf("写入位置: 偏移 %ld (0x%lx)\n", write_offset, write_offset);
    printf("数据大小: %d 字节\n", data_size);
    printf("数据摘要: %.60s...\n", write_data);
    
    // 1. 执行写入操作
    printf("\n1. 执行数据写入:\n");
    struct timeval write_start, write_end;
    gettimeofday(&write_start, NULL);
    
    ssize_t written = xdevice_pwrite(fd, write_data, data_size, write_offset);
    
    gettimeofday(&write_end, NULL);
    double write_time = (write_end.tv_sec - write_start.tv_sec) * 1000.0 + 
                        (write_end.tv_usec - write_start.tv_usec) / 1000.0;
    
    if (XDEVICE_FAILED(written)) {
        printf("  ✗ 写入失败: %s\n", xdevice_strerror(written));
        return 0;
    }
    printf("  ✓ 写入成功: %zd 字节，耗时 %.2fms\n", written, write_time);
    
    // 2. 强制同步到所有副本
    printf("\n2. 强制同步到副本:\n");
    struct timeval sync_start, sync_end;
    gettimeofday(&sync_start, NULL);
    
    int sync_ret = xdevice_fsync(fd);
    
    gettimeofday(&sync_end, NULL);
    double sync_time = (sync_end.tv_sec - sync_start.tv_sec) * 1000.0 + 
                       (sync_end.tv_usec - sync_start.tv_usec) / 1000.0;
    
    if (sync_ret != XDEVICE_OK) {
        printf("  ✗ 同步失败: %s\n", xdevice_strerror(sync_ret));
        return 0;
    }
    printf("  ✓ 同步完成，耗时 %.2fms\n", sync_time);
    
    // 3. 并发副本验证
    printf("\n3. 并发副本验证:\n");
    int num_replicas = stat.replicas > 0 ? stat.replicas : 1;  // 使用实际副本数
    int successful_replicas = concurrent_replica_verification(
        fd, write_offset, write_data, data_size, num_replicas);
    
    // 4. 深度一致性检查
    printf("\n4. 深度一致性检查:\n");
    int deep_check_passed = deep_consistency_check(fd, write_offset, write_data, data_size);
    
    // 5. 传统的逐个验证（保持兼容性）
    printf("\n5. 传统副本验证:\n");
    int traditional_success = 0;
    for (int replica = 0; replica < num_replicas; replica++) {
        usleep(10000);  // 10ms延迟
        if (verify_replica_data(fd, write_offset, write_data, data_size, replica + 1)) {
            traditional_success++;
        }
    }
    
    // 6. 综合评估
    printf("\n6. 综合评估:\n");
    int replica_consistency_rate = (successful_replicas * 100) / num_replicas;
    int traditional_consistency_rate = (traditional_success * 100) / num_replicas;
    
    printf("  并发验证: %d/%d (%.1f%%)\n", 
           successful_replicas, num_replicas, replica_consistency_rate / 1.0);
    printf("  传统验证: %d/%d (%.1f%%)\n", 
           traditional_success, num_replicas, traditional_consistency_rate / 1.0);
    printf("  深度检查: %s\n", deep_check_passed ? "通过" : "失败");
    
    int overall_success = (successful_replicas == num_replicas) && 
                         (traditional_success == num_replicas) && 
                         deep_check_passed;
    printf("  整体结果: %s\n", overall_success ? "✓ 完全成功" : "✗ 存在问题");
    
    return overall_success;
}

/* 循环写入测试 - 验证分布式复制 */
int continuous_write_test() {
    printf("=== XDevice 真实分布式复制验证测试 ===\n");
    
    // 初始化XDevice，使用本地测试配置
    const char* config_path = "/home/chenhg/xDevice/config/test_cluster.conf";
    printf("使用配置文件: %s\n", config_path);
    
    int ret = xdevice_init(config_path);
    if (ret != XDEVICE_OK) {
        fprintf(stderr, "Failed to initialize XDevice: %s\n", xdevice_strerror(ret));
        return -1;
    }
    
    printf("XDevice初始化成功 (版本 %s)\n", xdevice_version());
    
    // 检查集群健康状态
    xdevice_health_t health;
    int health_status = xdevice_health_check(&health);
    
    if (health_status > 0) {
        printf("集群状态健康:\n");
        printf("  活跃节点: %d / %d\n", health.active_nodes, health.total_nodes);
        printf("  可用性: %.1f%%\n", health.availability * 100);
        printf("  有领导者: %s\n", health.has_leader ? "是" : "否");
    } else {
        printf("集群状态不健康，但继续测试...\n");
    }
    
    // 打开用于测试的设备
    xdevice_fd_t fd = xdevice_open("database", XDEVICE_O_RDWR, 0);
    if (!XDEVICE_FD_VALID(fd)) {
        fprintf(stderr, "无法打开设备 'database': %s\n", xdevice_strerror(fd));
        xdevice_cleanup();
        return -1;
    }
    
    printf("成功打开设备 'database' (fd=%d)\n", fd);
    
    // 获取设备信息
    xdevice_stat_t stat;
    if (xdevice_fstat(fd, &stat) == XDEVICE_OK) {
        printf("设备信息:\n");
        printf("  名称: %s\n", stat.name);
        printf("  大小: %lu bytes (%.2f MB)\n", stat.size, stat.size / (1024.0 * 1024.0));
        printf("  副本数: %d (健康: %d)\n", stat.replicas, stat.healthy_replicas);
        printf("  块大小: %u bytes\n", stat.blksize);
    }
    
    printf("\n开始增强型真实数据写入和副本验证测试...\n");
    printf("测试特性:\n");
    printf("  • 高唯一性数据生成（时间戳+随机数+哈希）\n");
    printf("  • 多副本并发读取验证\n");
    printf("  • 深度一致性重复检查\n");
    printf("  • 详细性能和一致性统计\n");
    printf("  • 传统验证兼容性检查\n");
    printf("每次写入都会:\n");
    printf("  1. 写入唯一的真实数据\n");
    printf("  2. 同步到所有 %d 个副本\n", stat.replicas);
    printf("  3. 并发从每个副本读取验证数据一致性\n");
    printf("  4. 深度一致性检查（10轮随机间隔读取）\n");
    printf("  5. 传统逐个副本验证\n");
    printf("按 Ctrl+C 停止测试\n\n");
    
    // 设置信号处理
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);
    
    srand(time(NULL));  // 初始化随机数生成器
    
    int write_count = 0;
    int successful_writes = 0;
    time_t start_time = time(NULL);
    
    while (running && write_count < 50) {  // 限制最多50次测试，避免无限循环
        printf("\n" "============================================================" "\n");
        
        // 执行增强的副本写入测试
        if (real_replica_write_test(fd, "database", write_count + 1)) {
            successful_writes++;
            printf("\n🎉 测试轮次 #%04d 完全成功！所有副本验证都通过\n", write_count + 1);
        } else {
            printf("\n❌ 测试轮次 #%04d 存在问题，副本一致性验证失败\n", write_count + 1);
        }
        
        write_count++;
        
        // 每5次测试显示详细进度
        if (write_count % 5 == 0) {
            time_t elapsed = time(NULL) - start_time;
            double success_rate = (double)successful_writes / write_count * 100.0;
            double test_rate = elapsed > 0 ? (double)write_count / elapsed : 0.0;
            
            printf("\n" "------------------------------------------------------------" "\n");
            printf("📊 详细进度报告 - 已完成 %d 次测试:\n", write_count);
            printf("  ✅ 成功验证: %d 次\n", successful_writes);
            printf("  ❌ 失败次数: %d 次\n", write_count - successful_writes);
            printf("  📈 成功率: %.1f%%\n", success_rate);
            printf("  ⏱️  用时: %ld 秒\n", elapsed);
            printf("  🚀 测试速度: %.2f 次/秒\n", test_rate);
            printf("  🎯 预计剩余: %.0f 秒\n", 
                   test_rate > 0 ? (50 - write_count) / test_rate : 0);
            
            if (success_rate >= 100.0) {
                printf("  🌟 状态: 完美！所有副本都保持一致\n");
            } else if (success_rate >= 90.0) {
                printf("  ✨ 状态: 优秀，偶有小问题\n");
            } else if (success_rate >= 70.0) {
                printf("  ⚠️  状态: 良好，但需关注一致性\n");
            } else {
                printf("  🚨 状态: 需要检查，副本一致性问题较多\n");
            }
            printf("" "------------------------------------------------------------" "\n");
        }
        
        // 测试间隔
        printf("等待 1 秒后进行下一次测试...\n");
        sleep(1);
    }
    
    printf("\n" "============================================================" "\n");
    printf("🏁 增强型分布式副本一致性测试完成\n");
    printf("" "============================================================" "\n");
    time_t total_time = time(NULL) - start_time;
    double success_rate = write_count > 0 ? (double)successful_writes / write_count * 100.0 : 0.0;
    double avg_test_time = total_time > 0 ? (double)total_time / write_count : 0.0;
    
    printf("📈 最终统计报告:\n");
    printf("  总测试轮次: %d\n", write_count);
    printf("  完全成功次数: %d\n", successful_writes);
    printf("  失败次数: %d\n", write_count - successful_writes);
    printf("  整体成功率: %.1f%%\n", success_rate);
    printf("  总测试时间: %ld 秒 (%.1f 分钟)\n", total_time, total_time / 60.0);
    printf("  平均测试速度: %.2f 次/秒\n", total_time > 0 ? (double)write_count / total_time : 0.0);
    printf("  单次测试用时: %.1f 秒\n", avg_test_time);
    
    printf("\n🎯 质量评估:\n");
    if (success_rate >= 100.0) {
        printf("  💎 评级: 完美 (Perfect)\n");
        printf("  🎉 所有测试都成功！分布式复制工作完美无缺！\n");
        printf("  ✨ 副本一致性: 100%% 可靠\n");
    } else if (success_rate >= 95.0) {
        printf("  🥇 评级: 优秀 (Excellent)\n");
        printf("  👏 绝大多数测试成功，分布式复制工作优良！\n");
        printf("  ⭐ 副本一致性: 非常可靠\n");
    } else if (success_rate >= 80.0) {
        printf("  🥈 评级: 良好 (Good)\n");
        printf("  👍 大部分测试成功，但偶有副本不一致的情况\n");
        printf("  ⚠️  副本一致性: 基本可靠，建议监控\n");
    } else if (success_rate >= 60.0) {
        printf("  🥉 评级: 一般 (Fair)\n");
        printf("  😐 部分测试成功，副本一致性存在明显问题\n");
        printf("  🔍 副本一致性: 需要优化\n");
    } else {
        printf("  🚨 评级: 需要改进 (Needs Improvement)\n");
        printf("  ❌ 分布式复制存在严重问题，需要立即检查配置！\n");
        printf("  🆘 副本一致性: 不可靠，需要修复\n");
    }
    
    // 最后进行全面的数据完整性验证
    printf("\n🔍 全面数据完整性验证:\n");
    printf("正在随机验证最近写入的数据...\n");
    
    int integrity_checks = 5;
    int integrity_passed = 0;
    
    for (int i = 0; i < integrity_checks && i < write_count; i++) {
        // 验证最近几次写入的数据
        int check_round = write_count - i;
        
        // 使用确定性的偏移量计算（与写入时一致）
        off_t verify_offset = (check_round * 1024) % (2 * 1024 * 1024);
        
        char verify_buffer[512];
        ssize_t read_bytes = xdevice_pread(fd, verify_buffer, 300, verify_offset);
        
        if (read_bytes > 0) {
            verify_buffer[read_bytes] = '\0';
            printf("  位置 %ld (轮次 #%d): 读取 %zd 字节\n", verify_offset, check_round, read_bytes);
            printf("    内容摘要: %.60s...\n", verify_buffer);
            
            // 检查数据格式是否正确（包含我们的测试标识）
            if (strstr(verify_buffer, "ENHANCED_TEST") != NULL && 
                strstr(verify_buffer, "database") != NULL) {
                printf("    ✅ 数据格式正确，包含测试标识\n");
                integrity_passed++;
            } else {
                printf("    ❌ 数据格式异常，缺少测试标识\n");
                printf("    🔍 检查内容: %s\n", 
                       strstr(verify_buffer, "ENHANCED_TEST") ? "有ENHANCED_TEST" : "无ENHANCED_TEST");
            }
        } else {
            printf("  位置 %ld (轮次 #%d): ❌ 读取失败\n", verify_offset, check_round);
        }
    }
    
    double integrity_rate = integrity_checks > 0 ? (double)integrity_passed / integrity_checks * 100.0 : 0.0;
    printf("\n📊 数据完整性结果: %d/%d 通过 (%.1f%%)\n", 
           integrity_passed, integrity_checks, integrity_rate);
    
    if (integrity_rate >= 100.0) {
        printf("  🎯 数据完整性: 完美！所有数据都正确存储\n");
    } else if (integrity_rate >= 80.0) {
        printf("  ✅ 数据完整性: 良好，大部分数据正确\n");
    } else {
        printf("  ⚠️  数据完整性: 存在问题，部分数据异常\n");
    }
    
    // 关闭设备和清理
    xdevice_close(fd);
    xdevice_cleanup();
    
    printf("\n真实分布式副本验证测试完成！\n");
    if (success_rate >= 100.0) {
        printf("✅ 所有数据都已安全写入到 %d 个副本节点，分布式复制工作完美！\n", stat.replicas);
    } else {
        printf("⚠️  部分数据复制存在问题，成功率: %.1f%%\n", success_rate);
    }
    
    return success_rate >= 80.0 ? 0 : -1;
}

/* 并发写入测试 - 验证多个并发操作的复制一致性 */
int concurrent_write_test() {
    printf("\n=== 并发写入真实副本验证测试 ===\n");
    
    const char* config_path = "/home/chenhg/xDevice/config/test_cluster.conf";
    printf("使用配置文件: %s\n", config_path);
    
    if (xdevice_init(config_path) != XDEVICE_OK) {
        return -1;
    }
    
    // 同时打开多个设备进行并发写入
    const char* devices[] = {"database", "logs", "cache"};
    const int device_count = sizeof(devices) / sizeof(devices[0]);
    xdevice_fd_t fds[device_count];
    
    // 打开所有设备
    for (int i = 0; i < device_count; i++) {
        fds[i] = xdevice_open(devices[i], XDEVICE_O_RDWR, 0);
        if (!XDEVICE_FD_VALID(fds[i])) {
            printf("无法打开设备 '%s'\n", devices[i]);
            // 关闭已打开的设备
            for (int j = 0; j < i; j++) {
                xdevice_close(fds[j]);
            }
            xdevice_cleanup();
            return -1;
        }
        printf("成功打开设备 '%s' (fd=%d)\n", devices[i], fds[i]);
    }
    
    printf("\n开始并发写入和副本验证测试...\n");
    printf("将同时向 %d 个设备写入数据，并验证每个设备的副本一致性\n", device_count);
    
    int total_tests = 0;
    int successful_tests = 0;
    
    // 并发写入到多个设备
    for (int round = 0; round < 10; round++) {
        printf("\n==================================================\n");
        printf("并发轮次 #%d:\n", round + 1);
        
        for (int dev = 0; dev < device_count; dev++) {
            printf("\n--- 设备 '%s' 测试 ---\n", devices[dev]);
            
            // 生成唯一的测试数据
            char data[512];
            time_t timestamp = time(NULL);
            int data_size = snprintf(data, sizeof(data),
                "CONCURRENT|Device:%s|Round:%d|Time:%ld|Random:%d|并发写入副本验证测试数据包含详细信息",
                devices[dev], round + 1, timestamp, rand() % 10000);
            
            off_t offset = round * 512;
            printf("写入数据到位置 %ld (大小: %d 字节)\n", offset, data_size);
            printf("数据: %.80s...\n", data);
            
            // 执行写入
            ssize_t written = xdevice_pwrite(fds[dev], data, data_size, offset);
            
            if (XDEVICE_FAILED(written)) {
                printf("❌ 写入失败: %s\n", xdevice_strerror(written));
                total_tests++;
                continue;
            }
            
            printf("✓ 写入成功: %zd 字节\n", written);
            
            // 强制同步
            int sync_ret = xdevice_fsync(fds[dev]);
            if (sync_ret != XDEVICE_OK) {
                printf("❌ 同步失败: %s\n", xdevice_strerror(sync_ret));
                total_tests++;
                continue;
            }
            
            printf("✓ 同步完成\n");
            
            // 验证副本数据
            printf("验证副本一致性:\n");
            int replica_success = 0;
            int total_replicas = 3;
            
            for (int replica = 0; replica < total_replicas; replica++) {
                usleep(5000);  // 5ms延迟模拟不同副本访问
                
                if (verify_replica_data(fds[dev], offset, data, data_size, replica + 1)) {
                    replica_success++;
                }
            }
            
            total_tests++;
            if (replica_success == total_replicas) {
                successful_tests++;
                printf("✅ 设备 '%s' 轮次 #%d: 所有副本数据一致\n", devices[dev], round + 1);
            } else {
                printf("❌ 设备 '%s' 轮次 #%d: 只有 %d/%d 副本数据一致\n", 
                       devices[dev], round + 1, replica_success, total_replicas);
            }
        }
        
        // 轮次间隔
        printf("\n等待 1 秒后进行下一轮测试...\n");
        sleep(1);
    }
    
    // 最终并发验证：同时读取所有设备的最后写入数据
    printf("\n==================================================\n");
    printf("=== 最终并发副本一致性验证 ===\n");
    
    for (int dev = 0; dev < device_count; dev++) {
        printf("\n验证设备 '%s' 的最终数据状态:\n", devices[dev]);
        
        // 读取最后几次写入的数据
        for (int check = 0; check < 3; check++) {
            off_t check_offset = (9 - check) * 512;  // 最后3次写入的位置
            char check_buffer[512];
            
            ssize_t read_bytes = xdevice_pread(fds[dev], check_buffer, 100, check_offset);
            if (read_bytes > 0) {
                check_buffer[read_bytes] = '\0';
                printf("  位置 %ld: %.60s...\n", check_offset, check_buffer);
                
                // 验证数据格式
                if (strstr(check_buffer, "CONCURRENT") != NULL && 
                    strstr(check_buffer, devices[dev]) != NULL) {
                    printf("    ✓ 数据格式正确\n");
                } else {
                    printf("    ❌ 数据格式异常\n");
                }
            } else {
                printf("  位置 %ld: 读取失败\n", check_offset);
            }
        }
    }
    
    // 输出测试结果
    printf("\n==================================================\n");
    printf("=== 并发副本验证测试结果 ===\n");
    double success_rate = total_tests > 0 ? (double)successful_tests / total_tests * 100.0 : 0.0;
    
    printf("总测试次数: %d\n", total_tests);
    printf("成功验证次数: %d\n", successful_tests);
    printf("成功率: %.1f%%\n", success_rate);
    
    if (success_rate >= 100.0) {
        printf("🎉 所有并发写入测试都成功！副本一致性完美！\n");
    } else if (success_rate >= 80.0) {
        printf("⚠️  大部分并发测试成功，但存在少量不一致\n");
    } else {
        printf("❌ 并发写入存在严重的副本一致性问题\n");
    }
    
    // 关闭所有设备
    for (int i = 0; i < device_count; i++) {
        xdevice_close(fds[i]);
    }
    
    xdevice_cleanup();
    printf("并发写入副本验证测试完成！\n");
    return success_rate >= 80.0 ? 0 : -1;
}

int main(int argc, char* argv[]) {
    printf("XDevice 分布式复制测试程序\n");
    printf("===========================\n");
    
    int test_mode = 1;  // 默认运行循环写入测试
    
    if (argc > 1) {
        test_mode = atoi(argv[1]);
    }
    
    printf("测试模式: %s\n", 
           test_mode == 1 ? "循环写入测试" : "并发写入测试");
    printf("说明: 每次写入都会自动触发分布式复制到所有副本节点\n\n");
    
    int result = 0;
    
    if (test_mode == 1) {
        result = continuous_write_test();
    } else if (test_mode == 2) {
        result = concurrent_write_test();
    } else {
        printf("使用方法: %s [1|2]\n", argv[0]);
        printf("  1 - 循环写入测试 (默认)\n");
        printf("  2 - 并发写入测试\n");
        return 1;
    }
    
    return result;
}
